import { IState, IAction, TODO_ACTION_TYPE, ITodo } from './../../components/TodoList/typings';

function todoReducer(state: IState, action: IAction): IState {
  const { type, payload } = action;

  switch (type) {
    case TODO_ACTION_TYPE.ADD_TODO:
      return {
        ...state,
        todoList: [...state.todoList, payload as ITodo],
      };
    case TODO_ACTION_TYPE.REMOVE_TODO:
      return {
        ...state,
        todoList: state.todoList.filter(todo => todo.id !== (payload as number)),
      };
    case TODO_ACTION_TYPE.TOGLE_TODO:
      return {
        ...state,
        todoList: state.todoList.map(todo => {
          return todo.id === payload
            ? {
                ...todo,
                completed: !todo.completed,
              }
            : {
                ...todo,
              };
        }),
      };
    default:
      return state;
  }
}

export { todoReducer };
